//作者:唐嘉诚
//测试院线
const express = require("express");
const router = express.Router();
const db = require("../model/db");

//作者:唐嘉诚
//添加一个院线
router.post("/", async (req, res) => {
    const data = await db.Cinema.create(req.body);
    res.send({
        code: 0,
        message: "",
        count: 0,
        data
    });
})

//作者:唐嘉诚
//删除一个院线
router.delete("/:id", async (req, res) => {
    const data = await db.Cinema.deleteOne({
        _id: req.params.id
    })
    res.send({
        code: 0,
        message: "",
        count: 0,
        data
    });
})

//作者:唐嘉诚
//修改一个院线
router.put("/:id", async (req, res) => {
    const data = await db.Cinema.updateOne({
        _id: req.params.id
    }, req.body)
    res.send({
        code: 0,
        message: "",
        count: 0,
        data
    });
})

//作者:唐嘉诚
//分页查询所有院线
router.get("/", async (req, res) => {
    if (!req.query.field) {
        req.query.field = "_id";
    }
    if (!req.query.sort) {
        req.query.sort = "asc";
    }
    let s = req.query.field;
    if (req.query.sort === "desc") {
        s = "-" + s;
    }
    //分页
    if (!req.query.page) {
        req.query.page = 1;
    }
    if (!req.query.limit) {
        req.query.limit = 10;
    }
    const page = parseInt(req.query.page);
    const limit = parseInt(req.query.limit);
    let condition={};
    if(req.query.key){
        const exp=new RegExp(req.query.key,"i");
        condition={
            $or:[
                {name:{$regex:exp}},
                {tel:{$regex:exp}},
                {addr:{$regex:exp}}
            ]        
        };
    }
    const data = await db.Cinema.find(condition).sort(s).skip((page - 1) * limit).limit(limit);
    const count = await db.Cinema.countDocuments(condition);
    res.send({
        code: 0,
        message: "",
        count,
        data
    });
})

//作者:唐嘉诚
//查询一个院线
// 修改查询院线返回格式 作者：黄萌
router.get("/:id",async(req,res)=>{
    const data=await db.Cinema.findById(req.params.id);
    res.send({
        code: 0,
        message: "",
        data
    });
})

module.exports = router;